package com.sky.aspect;

import com.sky.annotation.AutoFile;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Aspect
@Component
@Slf4j

public class AutoFileAspect {


    @Before("@annotation(com.sky.annotation.AutoFile)")
    public void autoFill(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();

        Method method = signature.getMethod();
        AutoFile annotation = method.getAnnotation(AutoFile.class);
        OperationType  operationType = annotation.value();

        Object[] args = joinPoint.getArgs();
        if(args == null || args.length == 0){
            log.info("当前方法没有参数");
            return;
        }

        Object entry = args[0];

        Long c = BaseContext.getCurrentId();
        LocalDateTime now = LocalDateTime.now();


        if (operationType == OperationType.INSERT) {
            try {
                log.info("当前方法是新增操作");
                Method setCreateTime = entry.getClass().getDeclaredMethod("setCreateTime", LocalDateTime.class);
                setCreateTime.invoke(entry,now);

                Method setCreateUser = entry.getClass().getDeclaredMethod("setCreateUser", Long.class);
                setCreateUser.invoke(entry,c);

                Method setUpdateTime = entry.getClass().getDeclaredMethod("setUpdateTime", LocalDateTime.class);
                setUpdateTime.invoke(entry,now);

                Method setUpdateUser = entry.getClass().getDeclaredMethod("setUpdateUser", Long.class);
                setUpdateUser.invoke(entry,c);
            } catch (Exception e) {
                log.info("没有对应的set方法");
                e.printStackTrace();
            }
        }else {

            try {
                log.info("当前方法是更新操作");
                Method setUpdateTime = entry.getClass().getDeclaredMethod("setUpdateTime", LocalDateTime.class);
                setUpdateTime.invoke(entry,now);

                Method setUpdateUser = entry.getClass().getDeclaredMethod("setUpdateUser", Long.class);
                setUpdateUser.invoke(entry,c);
            } catch (Exception e) {
                log.info("没有对应的set方法");
                e.printStackTrace();
            }
        }
    }
}
